<template>
	<view>
		<!-- <NavBar is-scroll="">房间</NavBar> -->
		<NavBar title="房间" :isScroll="false" isTitle />
		<!-- <u-navbar leftIconSize="0" title="房间" bgColor="transparent" placeholder></u-navbar> -->
		<view class="box">
			<div class="img zdy-flex">
				<image :src="myInfo.avatarUrl || '/static/img/housing/lxr.png'" mode=""></image>
				<view class="nickNameSty">{{ myInfo.nickName }},祝你玩的开心~</view>
			</div>
			<view class="integralBox">
				<view class="detail zdy-flex zdy-flex-between-center">
					我的积分
					<div class="rightIcon" @click="recorShow = true">
						<u-icon name="list-dot" size="24" color="#000000" bold></u-icon>
						<span>明细</span>
					</div>
				</view>
				<view class="zdy-flex zdy-flex-between-center" style="font-size: 64rpx">
					{{ myInfo.newIntegral || 0 }}
					<view class="upload zdy-flex zdy-flex-center" @click="getRecord()">
						<u-icon name="reload" size="20" color="#ffffff" bold></u-icon>
					</view>
				</view>
			</view>
			<view class="menu zdy-flex zdy-flex-between-center">
				<view class="finish zdy-flex zdy-flex-align-center" @click="endShow = true">
					<u-icon name="close-circle" size="15" color="red"></u-icon>
					<span>结束本局</span>
				</view>
				<view class="finish inviteImg" @click="getImg">
					<u-icon name="chat" size="15" color="green"></u-icon>
					<span>二维码邀请</span>
				</view>
			</view>
			<view class="listBox">
				<view class="item zdy-flex zdy-flex-align-center" v-for="(item, index) in userList" :key="index">
					<image :src="item.avatarUrl" mode=""></image>
					<span class="nickname">{{ item.nickName }}</span>
					<span class="minute" :style="{ color: item.newIntegral >= 0 ? 'red' : 'green' }">{{ item.newIntegral }}分</span>
					<view class="shift" @click="transfer(item)">转账</view>
				</view>
			</view>
		</view>
		<u-popup :customStyle="{ borderRadius: '10rpx' }" :show="imgShow" mode="center" @close="imgShow = false" :safeAreaInsetBottom="false">
			<view class="popupBox">
				<image style="width: 360rpx; height: 360rpx; display: block; margin: 0 auto" :src="record.codeImg"></image>
			</view>
		</u-popup>
		<!-- 记录 -->
		<u-popup :round="10" :customStyle="{ height: '800rpx' }" :show="recorShow" mode="bottom" @close="recorShow = false">
			<view class="recordBox">
				<u-cell-group :border="false" v-if="record.recordList.length">
					<u-cell v-for="(item, index) in record.recordList" :key="index" :value="item.payName" :label="item.createDate" center>
						<view style="color: green" slot="title">{{ -item.payMoney }}</view>
						<view slot="value">
							<text style="font-weight: bold">{{ item.nickName }} 支付给 {{ item.payName }}</text>
						</view>
					</u-cell>
				</u-cell-group>
				<u-empty marginTop="200rpx" v-else mode="history"></u-empty>
			</view>
		</u-popup>
		<u-keyboard
			ref="uKeyboard"
			mode="number"
			:show="payShow"
			@confirm="payConfirm"
			@cancel="payShow = false"
			@close="payShow = false"
			@change="valueChange"
			@backspace="backspace"
			:showTips="false"
		>
			<view class="">
				<u--input placeholder="请输入内容" disabled shape="circle" border="surround" v-model="transferValue"></u--input>
			</view>
		</u-keyboard>

		<u-modal showCancelButton confirmColor="#FF700D" @confirm="handleSubmit" @cancel="endShow = false" :borderBottom="false" :show="endShow" title="是否结束对局"></u-modal>
	</view>
</template>

<script>
import { getCodImg, uploadFiles } from '@/api/user.js';
import upImg from '@/utils/upImg.js';
import { getRecord, putRecord, endRecord, payMoney } from '@/api/record.js';
export default {
	data() {
		return {
			payShow: false,
			imgShow: false,
			recorShow: false,
			endShow: false,
			transferValue: '',
			intervalId: '',
			record: {
				recordList: []
			},
			transferInfo: {},
			userInfo: uni.getStorageSync('userInfo')
		};
	},
	onPullDownRefresh() {
		this.getRecord();
	},
	onLoad(option) {
		this.recordId = option.recordId;
		this.getRecord();
	},
	onShow() {
		this.intervalId = setInterval(() => {
			this.getRecord();
		}, 6000);
	},
	onUnload() {
		clearInterval(this.intervalId);
	},
	onHide() {
		clearInterval(this.intervalId);
	},
	computed: {
		myInfo() {
			if (this.record.userList) {
				return this.record.userList.filter((item) => {
					return item.openid == this.userInfo.openid;
				})[0];
			} else {
				return {};
			}
		},
		userList() {
			if (this.record.userList) {
				return this.record.userList.filter((item) => {
					return item.openid != this.userInfo.openid;
				});
			} else {
				return [];
			}
		}
	},
	methods: {
		getRecord() {
			getRecord({ id: this.recordId })
				.then((record) => {
					record.recordList.reverse();
					this.record = record;
					// console.log(record, 'recordrecord');
					if (record.status == 0) {
						this.$Message('游戏已结束');
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				})
				.finally(() => {
					uni.stopPullDownRefresh(); // 停止下拉刷新
				});
		},
		transfer(item) {
			this.transferInfo = item;
			this.transferValue = '';
			this.payShow = true;
		},
		valueChange(val) {
			this.transferValue = this.transferValue + '' + val;
		},
		backspace() {
			if (this.transferValue.length) {
				this.transferValue = this.transferValue.slice(0, -1);
			}
		},
		atob(input) {
			const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
			let str = input.replace(/=+$/, '');
			let output = '';

			if (str.length % 4 === 1) {
				throw new Error('InvalidLengthError');
			}

			for (let i = 0, len = str.length; i < len; i += 4) {
				const a = chars.indexOf(str.charAt(i));
				const b = chars.indexOf(str.charAt(i + 1));
				const c = chars.indexOf(str.charAt(i + 2));
				const d = chars.indexOf(str.charAt(i + 3));
				const sum = (a << 18) | (b << 12) | (c << 6) | d;
				output += String.fromCharCode((sum >> 16) & 0xff, (sum >> 8) & 0xff, sum & 0xff);
			}

			return output;
		},
		// 将 Base64 转换为二进制数据（ArrayBuffer）
		base64ToArrayBuffer(base64) {
			const binaryString = this.atob(base64.split(',')[1]); // Base64 解码
			const len = binaryString.length;
			const bytes = new Uint8Array(len);
			for (let i = 0; i < len; i++) {
				bytes[i] = binaryString.charCodeAt(i);
			}
			return bytes.buffer;
		},
		// 上传 Base64 图片
		uploadBase64Image(base64Image) {
			// 获取文件系统管理器
			const fileSystemManager = wx.getFileSystemManager();
			// 定义临时文件路径
			const filePath = `${wx.env.USER_DATA_PATH}/temp_image.png`;
			// 将 Base64 转为二进制
			const arrayBuffer = this.base64ToArrayBuffer(base64Image);
			const that = this;
			// 将二进制数据写入为临时文件
			fileSystemManager.writeFile({
				filePath: filePath,
				data: arrayBuffer,
				encoding: 'binary',
				success: () => {
					upImg(filePath)
						.then(async (codeImg) => {
							await putRecord({
								...that.record,
								codeImg
							});
							that.record.codeImg = codeImg;
							this.imgShow = true;
						})
						.finally(() => {
							uni.hideLoading();
						});
				},
				fail: (err) => {
					uni.hideLoading();
					console.error('写入临时文件失败:', err);
				}
			});
		},
		async getImg() {
			if (!this.record.codeImg) {
				uni.showLoading();
				const img = await getCodImg({ scene: this.recordId, env_version: wx.getAccountInfoSync().miniProgram.envVersion, check_path: false, page: 'bill/myBill' });
				let codeImg = 'data:image/png;base64,' + uni.arrayBufferToBase64(img);
				this.uploadBase64Image(codeImg);
			} else {
				this.imgShow = true;
			}
		},
		handleSubmit() {
			endRecord(this.record).then((res) => {
				this.$Message('欢迎下次光临');
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			});
		},
		async payConfirm() {
			const { recordId, nickName, openid } = this.userInfo;
			const recordData = JSON.parse(JSON.stringify(this.record));
			const newRecord = {
				nickName,
				payMoney: this.transferValue,
				recordId,
				createDate: this.$filterTime(),
				payName: this.transferInfo.nickName,
				payId: this.transferInfo.openid
			};
			uni.showLoading();
			payMoney(newRecord)
				.then((res) => {
					this.payShow = false;
					this.getRecord();
				})
				.finally(() => {
					uni.hideLoading();
				});
		}
	}
};
</script>

<style>
page {
	background: linear-gradient(180deg, #94ceff 0%, #f5f5f5 20%, #cccccc 100%);
}
</style>

<style scoped lang="scss">
::v-deep .u-input--radius {
	border-radius: 0 !important;
}
.box {
	padding: 30rpx;
	.img {
		margin-bottom: 30rpx;
		align-items: flex-end;
		image {
			box-shadow: 0px 5rpx 10rpx rgba(0, 0, 0, 0.5); /* 阴影效果 */
			border-radius: 50%;
			width: 100rpx;
			height: 100rpx;
		}
		.nickNameSty {
			font-size: 25rpx;
			color: #a9a3a3;
		}
	}
	.integralBox {
		padding: 30rpx;
		border-radius: 20rpx;
		background-color: #446bd6;
		color: #ffffff;
		font-size: 36rpx;
		font-weight: bold;
		.rightIcon {
			position: relative;
			span {
				font-size: 20rpx;
				position: absolute;
				left: 10rpx;
				top: -25%;
				background-color: red;
				border: 1rpx solid #ffffff;
				width: 60rpx;
				border-radius: 20rpx;
				text-align: center;
			}
		}
		.detail {
			margin-bottom: 40rpx;
		}
		.upload {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			border: 1rpx solid #ffffff;
		}
	}
}
.menu {
	margin: 30rpx 0;
	.finish {
		width: fit-content;
		border-radius: 50rpx;
		padding: 10rpx 15rpx;
		color: red;
		background-color: #ffffff;
		border: 1rpx solid red;
		span {
			margin-left: 10rpx;
		}
	}
	.inviteImg {
		color: green;
		border: 1rpx solid green;
	}
}
.listBox {
	margin-bottom: 50rpx;
	.item {
		margin-bottom: 10rpx;
		background-color: #ffffff;
		padding: 30rpx;
		border-radius: 15rpx;
		font-size: 30rpx;
		image {
			margin-right: 10rpx;
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
		}
		.nickname {
			font-weight: bold;
		}
		.minute {
			margin-left: auto;
			margin-right: 10rpx;
			color: red;
		}
		.shift {
			background-color: #446bd6;
			padding: 10rpx 35rpx;
			border-radius: 50rpx;
			color: #ffffff;
		}
	}
}
.popupBox {
	padding: 50rpx;
}
::v-deep .u-input__content__field-wrapper__field {
	text-align: center !important;
}
.recordBox {
	padding: 30rpx;
	height: 850rpx;
	overflow-y: auto;
}
</style>
